﻿using System;
using UnityEngine;

namespace ZyGame
{
    class IntervalTimeSchedule : ISchedule
    {
        private float time;
        private float interval;
        private Action callback;
        private ScheduleCancelToken cancelToken;
        public bool isCompletion { get; private set; } = false;

        public IntervalTimeSchedule(ScheduleCancelToken cancelToken, float time, Action action)
        {
            this.time = Time.realtimeSinceStartup;
            cancelToken.Register(CancelSchedule);
            this.cancelToken = cancelToken;
            this.callback = action;
            this.isCompletion = false;
            this.interval = time;
        }

        private void CancelSchedule()
        {
            isCompletion = true;
        }


        public void Execute()
        {
            if (isCompletion)
            {
                return;
            }

            if (Time.realtimeSinceStartup - time < interval)
            {
                return;
            }

            time = Time.realtimeSinceStartup;
            callback?.Invoke();
        }

        public void Dispose()
        {
            cancelToken = null;
            callback = null;
            time = 0;
            interval = 0;
        }

        public void Restart()
        {
            isCompletion = false;
            time = Time.realtimeSinceStartup;
            cancelToken.Restart();
        }
    }
}